package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.clients.UserClient;
import com.leyou.user.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    private final UserClient userClient;

    private final JwtUtils jwtUtils;

    private final StringRedisTemplate redisTemplate;

    public UserAuthServiceImpl(UserClient userClient, JwtUtils jwtUtils, StringRedisTemplate redisTemplate) {
        this.userClient = userClient;
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {

        UserDTO userDTO = this.userClient.queryUserWithPass(username, password);

        if (null == userDTO || userDTO.getId() == null) {
            throw new LyException(401, "用户名或密码错误");
        }

        UserDetail userDetail = new UserDetail();
        userDetail.setId(userDTO.getId());
        userDetail.setUsername(userDTO.getUsername());

        //TODO 把userDTO加工成token，要利用jwt
        String token = jwtUtils.createJwt(userDetail);

        Cookie cookie = new Cookie("LY_TOKEN", token);
        cookie.setDomain("leyou.com");
        cookie.setPath("/");
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }

    @Override
    public void userLogout(HttpServletRequest request, HttpServletResponse response) {

        String token = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);

        //目的是删除redis中jti，如果已经不在了，则会报错，不处理
        try {
            Payload payload = jwtUtils.parseJwt(token);
            String key = RedisConstants.JTI_KEY_PREFIX + payload.getUserDetail().getUsername();

            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
            }
        } catch (Exception e) {
        }

        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME,"");
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setDomain("leyou.com");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

    }
}